package bdddaosimpl;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import bdd.beans.DBLink;
import bdd.beans.Typeposte;
import bdd.beans.Ue;
import bdddaos.DAOTypeposte;
import bdddaos.DAOTypeposte;

public class DAOTypeposteImpl implements DAOTypeposte {

	private DBLink dblink;
	
	public DAOTypeposteImpl() {
		dblink = new DBLink();
	}
	
	@Override
	public Typeposte save(Typeposte o) {
		try {
			this.dblink.connexion();
			String s = "INSERT INTO TYPEPOSTE (TYPE, DESCRIPTION, NBHEURES)" + " VALUES (" + o.getType() + ", " + o.getDescription() + ","+o.getNbheures() + ")";
			this.dblink.setPst(this.dblink.getConnection().prepareStatement(s));
			this.dblink.getPst().executeQuery();
			DAOOutils outil = new DAOOutils();
			o.setNumposte(outil.findMaxId("TYPEPOSTE", "NUMPOSTE"));
		}
		catch(SQLException se) {
			System.out.println("Erreur de requete : " + se);
		}
		finally{
			this.dblink.deconnexion();
		}
		return o;
	}

	@Override
	public Typeposte find(Integer id) {
		dblink.connexion();
		
		String query = "select * from typeposte where numposte = "+id;
		
		try {
			PreparedStatement pst = dblink.getConnection().prepareStatement(query); 
			ResultSet rs = pst.executeQuery();
			
			if(rs.next()) {
				Typeposte tp = new Typeposte();
				
				tp.setDescription(rs.getString("DESCRIPTION"));
				tp.setNbheures(rs.getInt("NBHEURES"));
				tp.setNumposte(rs.getInt("NUMPOSTE"));
				tp.setType(rs.getString("TYPE"));
				
				tp.setEnseignants(null);
				
				pst.close();
				dblink.deconnexion();
				
				return tp;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		dblink.deconnexion();
		
		return null;
	}

	@Override
	public List<Typeposte> findAll() {
		List<Typeposte> listeRetour = new ArrayList<Typeposte>();
		try {
			this.dblink.connexion();
			this.dblink.setPst(this.dblink.getConnection().prepareStatement("SELECT * FROM TYPEPOSTE"));
			ResultSet rs = this.dblink.getPst().executeQuery();
			while(rs.next()) {
				Typeposte retour = new Typeposte();
				retour.setDescription(rs.getString("DESCRIPTION"));
				retour.setNbheures(rs.getInt("NBHEURES"));
				retour.setNumposte(rs.getInt("NUMPOSTE"));
				retour.setType(rs.getString("TYPE"));
				
				retour.setEnseignants(null);
				listeRetour.add(retour);
			}
		}
		catch(SQLException se) {
			System.out.println("Erreur de requete : " + se);
		}
		finally {
			this.dblink.deconnexion();
		}
		return listeRetour;
	}

	@Override
	public void update(Typeposte transientObject) {
		// TODO Auto-generated method stub
	}

	@Override
	public void delete(Typeposte persistentObject) {
		// TODO Auto-generated method stub
	}

}
